package com.modules.persistence;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

public class BaseSpecification<T> implements Specification<T> {
	
	
	private SearchFilter filter;
	public BaseSpecification(SearchFilter filter){
		this.filter = filter;
	}
	
	@Override
	public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
		String[] names = StringUtils.split(filter.getFieldName(), ".");
		Path expression = root.get(names[0]);
		for (int i = 1; i < names.length; i++) {
			expression = expression.get(names[i]);
		}
		switch (filter.getOperator()) {
		case EQ:
			return builder.equal(expression, filter.getValue());
			
		case LIKE:
			return builder.like(expression, "%" + filter.getValue() + "%");
			
		case GT:
			return builder.greaterThan(expression, (Comparable) filter.getValue());
			
		case LT:
			return builder.lessThan(expression, (Comparable) filter.getValue());
			
		case GTE:
			return builder.greaterThanOrEqualTo(expression, (Comparable) filter.getValue());
			
		case LTE:
			return builder.lessThanOrEqualTo(expression, (Comparable) filter.getValue());
		
		}
		return null;
	}

}
